package leetcode_400;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 *@author 周杨
 *EvaluateDivision_399 输出除法结果值 给出查询框架
 *describe:建立有向图 AC 97%
 *2018年7月16日 上午10:53:17
 */
public class EvaluateDivision_399 {
	 class Info {
	        String den;
	        double val;
	        Info(String den, double val) { this.den = den; this.val = val; }
	    }
	HashMap<String, List<Info>> map;
	public double[] calcEquation(String[][] equations, double[] values, String[][] queries) {
		// build graph, use adjacent list
        map = new HashMap();
        for(int i = 0; i < equations.length; i++) {
            String[] equation = equations[i];
            if(!map.containsKey(equation[0])) map.put(equation[0], new ArrayList());
            map.get(equation[0]).add(new Info(equation[1], values[i]));
            
            if(!map.containsKey(equation[1])) map.put(equation[1], new ArrayList());
            map.get(equation[1]).add(new Info(equation[0], 1 / values[i]));
        }
        
        double[] result = new double[queries.length];
        for(int i = 0; i < result.length; i++) {
            result[i] = find(queries[i][0], queries[i][1], 1, new HashSet());
        }
        return result;
    }
	
	private double find(String start, String end, double value, Set<String> visited) {
        if(visited.contains(start)) return -1;
        if(!map.containsKey(start)) return -1;
        
        if(start.equals(end)) return value;
        visited.add(start);
        for(Info next : map.get(start)) {
            double sub = find(next.den, end, value * next.val, visited);
            if(sub != -1.0) return sub;
        }
        
        visited.remove(start);
        return -1;
    }
}
